import pymysql
from Spider.settings import MYSQL_CONFIG, MYSQL_TABLE_NAME


class SaveData(object):
    def __init__(self):
        self.db = pymysql.connect(**MYSQL_CONFIG)
        self.cursor = self.db.cursor(cursor=pymysql.cursors.DictCursor)
        self.n = 0
        
    def do_insert(self, item):
        sql = self.get_sql(item)
        data = tuple(item.values())
        try:
            self.cursor.execute(sql, data)
            self.db.commit()
            self.n += 1
            print('当前已入库数量:', self.n)
        except:
            self.db.rollback()
            print(item, '数据入库出错')

    def get_sql(self, item):
        table = MYSQL_TABLE_NAME
        keys = ','.join([key for key in item.keys()])
        value = ','.join(['%s'] * len(item))
        sql = f'insert into {table}({keys}) values ({value})'
        return sql
